<!--  -->
<template>
  <div class="app">
    <div class="flex mb-30">
      <div class="btn-back" @click="routerGoTo('MemberIndex')">
        <i class="el-icon-back"></i> 返回
      </div>
      <div class="line"></div>
      <div class="name">学员批量导入</div>
    </div>

    <el-upload
      class="upload-demo"
      action="http://1.14.239.98/backend/api/v1/member/import"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :on-success="sendSuccess"
      :on-exceed="handleExceed"
      :on-error="sendError"
      :before-upload="sendBefor"
      :data='usersData'
      :auto-upload='false'
      :on-change='handlechange'
      :show-file-list="false"
    >
      <el-button size="small" type="primary">点击上传文件</el-button>
      <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
    </el-upload>
  </div>
</template>

<script>
import Vue from 'vue';
// import func from 'vue-editor-bridge';
import XLSX  from "xlsx";
Vue.use(XLSX)
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
        users:[],
        usersData:{
            users:[]
        }
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    users:{
        handler(val,oldval){
            console.log('val',val);
            console.log('oldval',oldval);
            this.$request.post('/member/import',{
            users:val
        }).then(res=>{
            console.log(res);
            if(res.status == 0){
                this.$message('添加成功')
            }else{
                this.$message(res.message)
            }
            
        })
        }
    }
  },
  //方法集合
  methods: {
    routerGoTo(val) {
      this.$router.push({
        name: val,
        params: {
          id: this.$route.params.id,
        },
      });
    },
    handleRemove(file, fileList) {
      console.log('tianjia',file, fileList);

    },
    handlePreview(file) {
      //   console.log(file.files());
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
   async handlechange(file){
        console.log('1',file.raw);
        await this.readExcel(file.raw);
        console.log('this.users',this.users);
        
    },
    sendBefor(file) {
      
    //   this.readExcel(file)
    },
    sendSuccess(res) {
      console.log(res);
    },
    sendError(res) {
    //   console.log(res);
    },
   async readExcel(fileData) {
      let that = this;
    //   console.log(fileData);
      console.log(this,'this');
      const files = fileData;
      console.log(files);
      if (!files) {
        //如果没有文件
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
        this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
        return false;
      }
      const fileReader = new FileReader();
      fileReader.readAsBinaryString(files);
      fileReader.onload = (ev) => {
        console.log(1);
        try {
          const data = ev.target.result;
        //   console.log(data)
          console.log(4);
          const workbook = XLSX.read(data, {
            type: "binary",
          });
          console.log(2);
          console.log(workbook.SheetNames);
          const wsname = workbook.SheetNames[0]; //取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
          console.log(ws);
          that.users = []; //清空接收数据
          console.log(3);
          for (var i = 0; i < ws.length; i++) {
            var sheetData = [
              // 键名为绑定 el 表格的关键字，值则是 ws[i][对应表头名]
            ws[i]["手机号"],
            ws[i]["密码"],
            ws[i]["VIP"],
            ws[i]["VIP过期时间"],
            ws[i]["是否锁定（1锁定，0不锁定）"],
            ws[i]["标签"],
            //   mobile: ws[i]["手机号"],
            //   password: ws[i]["密码"],
            ];
            that.users.push(sheetData);
            // that.usersData.users=that.users;
          }
          console.log(that.users);
        //   this.$refs.upload.value = "";
        }
        catch (e) {
            console.log(e);
          return false;
        }
      };
      // 如果为原生 input 则应是 files[0]
    //   console.log(files.Prototype);
      
    //   fileReader.onload = ()=>{
        // console.log(fileReader);
    // }
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped lang="less">
.app {
  padding: 30px;
  border-radius: 15px;
  background-color: #fff;
  .btn-back {
    &:hover {
      color: #3ca7fa;
      cursor: pointer;
    }
  }
  .mt-30 {
    margin-top: 30px;
  }
  .ml-20 {
    margin-left: 20px;
  }
  .mr-20 {
    margin-right: 20px;
  }
  .mb-30 {
    margin-bottom: 30px;
  }
  .line {
    width: 1px;
    height: 14px;
    background-color: #d8d8d8;
    margin-right: 15px;
    margin-left: 15px;
  }
  .flex {
    width: 100%;
    display: flex;
  }
  .flex-spaceCenter {
    justify-content: center;
  }
  .flex-spaceBetween {
    justify-content: space-between;
  }
  .flex-alignCenter {
    align-items: center;
  }
}
</style>
